<template>
    <!-- <div class="loginPage"> -->
        <van-overlay :show="isform">
            <div class="flex justify-center items-center h-full flex-col">
                    <div class="w-[90%] flex justify-end md:pr-[10rem]  ">
                        <CommunityIcon @click="close"></CommunityIcon>
                        <!-- <img src="../assets/img/gb.png" class="w-[1.5rem] max-w-[1.5rem]  mb-1" alt="关闭" @click="isform = false"> -->
                    </div>
                    <div class="w-[90%] h-[20rem] max-w-[400px] bg-[#fff] rounded-lg flex justify-center  flex-col">
                        <div class=" flex justify-center font-bold"> 短信验证码登录</div>
                        <div class=" flex justify-center">
                            <div class="w-[85%]">
                                <van-form ref="form" class="mt-[1rem]">
                                    <van-field v-model="logininfo.phone" autocomplete="off" type="tel" maxlength="11" clearable name="tel"
                                        :rules="userTel" placeholder="请输入手机号" />
                                    <van-field v-model="logininfo.code" autocomplete="off" maxlength="6" center clearable
                                        placeholder="短信验证码" :rules="[{ required: true, message: '请填写验证码' }]"
                                        type="digit">
                                        <template #button>
                                            <van-button round type="success" style="height:2.5rem; width:7rem;"
                                                size="small" @click="sendCode" :disabled="disabled"
                                                color="rgb(246,120,72)" native-type="button">
                                                {{ codeMsg }}
                                            </van-button>
                                        </template>
                                    </van-field>
                                    <div class="mx-[0.426rem] mt-[1rem] flex justify-center">
                                        <van-button style="width:13rem;height: 2.5rem; " :loading="isloginbut" round
                                            type="success" size="large" color="rgb(246,120,72)" @click="onsubmit()">立即登录
                                        </van-button>
                                    </div>
                                    <div class=" h-full mx-[1rem] flex justify-center">
                                        <van-field name="radio" label="" whidth="1rem"
                                            :rules="[{ required: true, message: '请填写验证码' }]">
                                            <template #input class=" h-full flex justify-center">
                                                <van-checkbox v-model="logininfo.checked" class=""
                                                    checked-color="rgb(246,120,72)">
                                                </van-checkbox>
                                                <div class="ml-2 text-[0.8rem]">
                                                    我已同意<span
                                                        @click="agreement('https://sdk.nextjoy.com/init/init/getRegster?gid=34', '用户协议')"
                                                        class=" decoration-1 text-[rgb(246,120,72)]">用户协议</span>与<span
                                                        @click="agreement('https://sdk.nextjoy.com/init/init/getPrivacy?gid=34', '隐私协议')"
                                                        class=" decoration-1 text-[rgb(246,120,72)]">隐私协议</span>
                                                </div>
                                            </template>
                                        </van-field>
                                    </div>
                                </van-form>
                            </div>

                        </div>
                    </div>
            </div>
        </van-overlay>
        <van-dialog width="90%" styel="height:800px;" :showCancelButton=false v-model:show="isagreement">
            <iframe class="w-full h-[370px]" :src="iframepath" frameborder="0"></iframe>
        </van-dialog>
        <!-- <div>
            <img src="../assets/img/title.png" class="w-[100%]" alt="">
            <div class="mainbg h-[23rem] max-h-[23rem] md:h-[43rem] md:max-h-[43rem] w-full flex justify-start items-end">
                <div class="pb-[2.5rem] pl-[0.9rem] md:pb-[5rem] md:pl-[3rem]">
                    <img src="../assets/img/gamelogo.png" class="w-[5.5rem] md:w-[s10rem]" alt="">
                </div>
            </div>
            <div class=" absolute top-1 right-3" @click="agetitle()">
                <img src="../assets/img/12.png" class="w-[2.5rem]" alt="">
            </div>
        </div> -->
        <!-- 测试生成二维码 -->
        <!-- <vue-qr v-if="false" :logo-src="logoSrc" :size="191" :margin="0" :auto-color="true" :dot-scale="1"
            :text="appSrc" colorDark="red" colorLight="yellow" /> -->
        <!-- 未登录显示 -->
        <div class="loginbg">
            <div class="h-[15rem] flex justify-center items-center flex-col">
                <div class="text-[#865931] font-bold">请先登录游戏账号</div>
                <div
                    class="rounded-[1.5rem] bg-[#fdf6dc] mt-5 w-[6rem] h-[2.5rem] flex justify-center items-center">
                    <span class="text-[#865931]" @click="login()">登录</span>
                </div>
            </div>
        </div>
    <!-- </div> -->
</template>

<script>
import CommunityIcon from '../components/icons/IconCommunity.vue'
import { mapState, mapActions } from 'pinia'
import { useCounterStore } from '../stores/counter'
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import md5 from 'js-md5'
import wx from 'weixin-jsapi'
import qs from 'qs'
export default {
    data() {
        return {
            iframepath: '', //嵌入地址
            isagreement: false, //用户协议弹出层
            isagreementtitle: '', //弹出标题
            logoSrc: '',
            appSrc: 'weixin://wxpay/bizpayurl?pr=bkAhfrazz',
            // 按钮状态
            isloginbut: false,
            isform: true,
            logininfo: {
                phone: "",
                code: "",
                checked: ''
            },
            disabled: false,
            codeNum: 60,
            codeMsg: "获取验证码",
            userTel: [
                {
                    required: true,
                    message: "请输入手机号",
                    trigger: "onBlur"
                },
                {
                    validator: value => {
                        return /^1[23456789]\d{9}$/.test(value);
                    },
                    message: "请输入正确格式的手机号"
                }
            ]
        }
    },
    props:['isLoginShow'],
    computed: {
 
        ...mapState(useCounterStore, ['gid', 'path'])
    },
    created() {
    },
    components: {
        vueQr,
        CommunityIcon
    },
    methods: {
        agreement(item, title) {
            this.iframepath = item
            this.isagreementtitle = title
            this.isagreement = true
        },
        ...mapActions(useCounterStore, ['setuserserverlist']),
        // 生成二维码
        login() {
            this.isform = true
        },
        // 立即登陆
        onsubmit() {
       
            // 判断隐私协议是否勾选

            if (this.logininfo.checked == false || this.logininfo.checked == '') {
                this.$toast.fail('请先详细阅读并同意用户协议与隐私政策');
                return
            } else if (this.logininfo.phone == '') {
                this.$toast.fail('请先输入正确的手机号');
                return
            } else if (this.logininfo.code == '') {
                this.$toast.fail('请先输入正确的验证码');
                return
            } else {
                this.isloginbut = true
                // 进入登录操作
                
                // let loginmd5 = md5(`timestamp=${Date.parse(new Date())}&state=${localStorage.getItem('state')}&mobile_code=${this.logininfo.code}&mobile=${this.logininfo.phone}&gid=${this.gid}&code=${localStorage.getItem('code')}&key=N5Gp6yTpl1WybuQZ0MnbEVgZ2mKOlfRE`)
                let loginmd5 = md5(`timestamp=${Date.parse(new Date())}&mobile_code=${this.logininfo.code}&mobile=${this.logininfo.phone}&gid=${this.gid}&key=N5Gp6yTpl1WybuQZ0MnbEVgZ2mKOlfRE`)
                this.$http({
                    method: 'post',
                    url: `${this.path}/api/mtstore/login`,
                    data: qs.stringify({
                        mobile: this.logininfo.phone,
                        mobile_code: this.logininfo.code,
                        timestamp: Date.parse(new Date()),
                        sign: loginmd5.toUpperCase(),
                        gid: this.gid,
                    })
                }).then(res => {
                    console.log('登录成功后的', res)
                    if (res.data.status == '200') {
                        // 存储token
                        localStorage.setItem('token', res.data.data.user_token)
                        localStorage.setItem('userid', res.data.data.uid)

                        // 存储服务器数据
                        // this.setuserserverlist(res.data.data.role_list)

                        if(this.$route.path == '/signIn'){
                            this.isform = false
                            window.location.href = 'https://mtshop.nextjoy.com.cn/signIn'
                            // window.location.href = 'http://172.20.10.2:5176/signIn'
                        }else{
                            this.$router.push('/indexpage')
                        }
                        
                    } else {
                        this.$toast.fail('登录失败，请重新登录！', `${res.data.message}`);
                    }
                    this.isloginbut = false
                })
            }
        },
        sendCode() {
   
            // 验证手机号格式是否正确
            if (!this.userTel[1].validator(this.logininfo.phone)) {
                this.$toast.fail('请先输入正确的手机号');
                return
            }
           
            let mdsign = md5(`timestamp=${Date.parse(new Date())}&mobile=${this.logininfo.phone}&gid=${this.gid}&key=N5Gp6yTpl1WybuQZ0MnbEVgZ2mKOlfRE`)
          
            this.$http({
                method: 'post',
                url: `${this.path}/api/mtstore/sendcode`,
                data: qs.stringify({
                    mobile: this.logininfo.phone,
                    gid:this.gid,
                    timestamp: Date.parse(new Date()),
                    sign: mdsign.toUpperCase()
                })
            }).then(res => {
                console.log('成功返回的数据', res)
                if (res.data.status == '6001') {
                    this.$toast.fail(`${res.data.message}`);
                } else if (res.data.status == '10002') {
                    this.$toast.fail(`${res.data.message}`);
                } else if (res.data.status != '200') {
                    this.$toast.fail(`获取验证码失败${res.data.message}`);
                } else {
                    // 禁用按钮
                    this.disabled = true;
                    // 倒计时
                    let timer = setInterval(() => {
                        --this.codeNum;
                        this.codeMsg = `验证码(${this.codeNum})`;
                    }, 1000);
                    // 判断什么时候停止定时器
                    setInterval(() => {
                        clearInterval(timer);
                        this.codeNum = 60;
                        this.disabled = false;
                        this.codeMsg = "获取短信验证码";
                    }, 60000);
                }
            })

        },
        close(){
            this.isform = false     
            this.$emit('isLoginPopUp', this.isform);
        }
    }
}
</script>

<style scoped>
.loginPage{
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
}

</style>
